package cn.wittyneko.anim

import android.animation.*

/**
 * Animator 动画调用包装
 * Created by wittyneko on 2017/10/12.
 */
class ObjectAnim(val animator: ValueAnimator) : AnimListener {

    var listener: AnimListener? = null

    var isAnimEnd: Boolean = false
        protected set

    var isAnimCancel: Boolean = false
        protected set

    //是否反向
    private var _isAnimReverse: Boolean = true
    var isAnimReverse: Boolean
        get() {
            if (animator.isRunning) {
                return animator.isReversing
            } else {
                return _isAnimReverse
            }
        }
        internal set(value) {
            _isAnimReverse = value
        }

    //动画播放时间
    val animCurrentPlayTime: Long
        get() {
            if (animator.isRunning && isAnimReverse) {
                return animator.duration - animator.currentPlayTime
            } else {
                return animator.currentPlayTime
            }
        }

    init {
        animator.addListener(this)
        animator.addUpdateListener(this)
    }


    /**
     * 正向播放
     */
    open fun animStart() {
        when {
            animator.isRunning && isAnimReverse -> {
                reverse()
            }
            !animator.isRunning -> {
                start()
            }
        }
    }

    /**
     * 反向播放
     */
    open fun animReverse() {
        when {
            animator.isRunning && !isAnimReverse -> {
                reverse()
            }
            !animator.isRunning -> {
                reverse()
            }
        }
    }

    /**
     * 切换播放方向
     */
    open fun animTrigger(): Boolean {
        if (isAnimReverse) {
            animStart()
        } else {
            animReverse()
        }
        return isAnimReverse
    }

    fun start() {
        isAnimCancel = false
        isAnimEnd = false
        animator.start()
    }

    fun reverse() {
        isAnimCancel = false
        isAnimEnd = false
        animator.reverse()
    }

    fun end() {
        isAnimCancel = false
        isAnimEnd = true
        animator.end()
    }

    fun cancel() {
        isAnimCancel = true
        isAnimEnd = false
        animator.cancel()
    }

    override fun onAnimationUpdate(animation: ValueAnimator?) {
        listener?.onAnimationUpdate(animation)
    }

    override fun onAnimationStart(animation: Animator?) {
        listener?.onAnimationStart(animation)
    }

    override fun onAnimationEnd(animation: Animator?) {
        if ((animator.isStarted || animator.isRunning) && animation is ValueAnimator) {
            _isAnimReverse = animation.isReversing
        }
        listener?.onAnimationEnd(animation)
    }

    override fun onAnimationCancel(animation: Animator?) {
        listener?.onAnimationCancel(animation)
    }

    override fun onAnimationRepeat(animation: Animator?) {
        listener?.onAnimationRepeat(animation)
    }
}